package service

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"gomicrodemo/common"
	"gomicrodemo/user_service/model"
	"time"
)

func UserLogin(username string, password string) (string, string) {

	//根据用户名和密码查询数据库中对应用户的信息是否正确，正确则返回token，不正确则设置提示信息

	user := &model.User{}
	message := "success"
	token := ""

	db := common.GetDB()
	err := db.Model(user).Where("username = ?", username).Find(user).Error
	//如果没有从db中查询到对应的用户数据，则err!=nil
	if err != nil {
		message = "该用户不存在，请重新输入！"
		return message, token
	}

	//校验密码是否正确
	if password != user.Password {
		message = "密码错误，请重新输入！"
		return message, token
	}

	//登录校验成功则生成token令牌返回
	token = common.GetToken(user.Username, int(user.ID))
	return message, token
}

func UserRegistry(username string, password string, email string) (string, string) {

	nowtime := time.Now()              //获取当前时间
	year, month, day := nowtime.Date() //获取当前时间的年月日
	cretedat := time.Date(             //将年月日，时分秒，纳秒值0，关联的时区信息插入  获取time.Time类型
		year, month, day,
		nowtime.Hour(), nowtime.Minute(), nowtime.Second(), 0, nowtime.Location(),
	)
	updatedat := time.Date(
		year, month, day,
		nowtime.Hour(), nowtime.Minute(), nowtime.Second(), 0, nowtime.Location(),
	)

	models := gorm.Model{
		//CreatedAt: time.Unix(1624156388, 0),
		//UpdatedAt: time.Unix(1624156388, 0),
		CreatedAt: cretedat,
		UpdatedAt: updatedat,
	}
	//获取数据库连接
	db := common.GetDB()
	user := &model.User{
		username,
		password,
		email,
		1,
		username,
		models,
	}

	message := "success"
	token := ""

	db = db.Model(user)
	//modelstruct := db.NewScope(user).GetModelStruct()
	//tableName := modelstruct.TableName(db)
	//fmt.Printf("结构体:%v\n表名:%v",modelstruct,tableName)

	userByte, _ := json.Marshal(user)
	writer := gin.DefaultWriter
	writer.Write(userByte)

	if err := db.Create(&user).Error; err != nil {
		message = "fail"
		token = "err token"
	} else {
		token = "test token"
	}

	//defer db.Close()
	return message, token
}
